<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true">
        <el-form-item label="工厂">
          <el-select
            v-model="searchParam.plantId"
            placeholder="请输入工厂"
            clearable
            @keyup.enter="search"
            @change="changePlant(searchParam.plantId)"
            filterable
          >
            <el-option
              v-for="plant in plantList"
              :key="plant.id"
              :label="plant.organizationCode"
              :value="plant.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="存货编码">
          <!-- <el-select
            v-model="searchParam.materialIds"
            placeholder="请选择存货编码"
            clearable
            @keyup.enter="search"
            filterable
            @click="openDialogAdd"
          >
            <el-option
              v-for="item in materialIdsList"
              :key="item.id"
              :label="item.id"
              :value="item.id"
            />
          </el-select> -->

          <search-content-input
            :width="350"
            :isMultiple="true"
            :showSelectDevice="materialList"
            :plantId="searchParam.plantId"
            :maxCollapseTags="2"
            :disabled="searchParam.plantId == ''"
            @get-device="(id, object) => getDevice(id, object)"
          />
          <!-- <el-input
            v-model="searchParam.materialCode"
            placeholder="请输入存货编码"
            clearable
            @keyup.enter="search"
          /> -->
        </el-form-item>
        <!-- <el-form-item label="图号">
          <el-input
            v-model="searchParam.figureNumber"
            placeholder="请输入图号"
            clearable
            @keyup.enter="search"
          />
        </el-form-item> -->
        <!-- <el-form-item label="存货名称">
          <el-input
            v-model="searchParam.materialName"
            placeholder="请输入存货编码"
            clearable
            @keyup.enter="search"
          />
        </el-form-item> -->
        <el-form-item label="计划状态">
          <el-select
            v-model="searchParam.planState"
            placeholder="请选择计划状态"
            clearable
            @keyup.enter="search"
            filterable
          >
            <el-option
              v-for="item in useDictionary('plannedBatchType')"
              :key="item.value"
              :label="item.label"
              :value="Number(item.value)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="计划批次">
          <el-input
            v-model="searchParam.planBatch"
            placeholder="请输入计划批次"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <el-form-item label="计划年份">
          <el-select
            @keyup.enter="search"
            v-model="searchParam.planYear"
            placeholder="请选择计划年份"
            clearable
            @change="selectYear"
          >
            <el-option
              v-for="item in yearOptions"
              :key="item"
              :value="item"
              :label="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="计划月份">
          <el-select
            @keyup.enter="search"
            v-model="searchParam.planMonth"
            placeholder="请选择计划月份"
            clearable
            @change="selectMonth"
          >
            <el-option
              v-for="item in monthOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="计划周">
          <el-select
            @keyup.enter="search"
            v-model="searchParam.planWeek"
            placeholder="请选择计划周"
            clearable
            @change="selectWeek"
          >
            <el-option
              v-for="item in weekOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item> -->
        <el-form-item>
          <el-button type="primary" @click="search"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="reset1"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <!-- <el-button type="primary" @click="openDialog()"
          ><i-ep-plus />新增</el-button
        > -->
        <!-- <el-button type="primary" @click="issueOrders()" :loading="issueLoading"
          >下 达</el-button
        > -->
        <!-- <el-button
          type="primary"
          @click="changeSubmission()"
          :loading="changeSubLoading"
          >变更提交</el-button
        > -->
        <el-button type="danger" @click="closePlan()" :loading="closeLoading"
          >关 闭</el-button
        >
        <!-- <el-button type="danger" @click="deletePlan()" :loading="deleteLoading"
          >删 除</el-button
        > -->
        <el-button
          class="ml-3"
          @click="
            useDownload('/mes/mesplannedbatch/export', '计划批次', searchParam)
          "
        >
          <template #icon><i-ep-download /></template>导出</el-button
        >

        <!-- <el-button
          type="danger"
          plain
          :disabled="ids.length === 0"
          @click="handleTableDelete()"
          ><i-ep-delete />删除</el-button
        >
        <el-button
          class="ml-3"
          @click="
            useDownload('/mes/mesplannedbatch/export', '计划批次', searchParam)
          "
        >
          <template #icon><i-ep-download /></template>导出</el-button
        >-->
        <el-button @click="weekBatchImport">
          <template #icon><i-ep-upload /></template>关闭导入
        </el-button>
        <el-dialog
          :close-on-click-modal="false"
          title="计划批次数据导入"
          v-model="excelBox"
          width="555px"
        >
          <div>
            <el-button
              @click="
                useDownload(
                  '/mes/mesplannedbatch/exportTemp',
                  '计划批次上传模板',
                  searchParam
                )
              "
            >
              <template #icon>
                <i-ep-download />
              </template>
              计划批次上传模板下载
            </el-button>
          </div>
          <div style="margin-top: 10px">
            <input
              class="crop-input"
              type="file"
              name="image"
              accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
              ref="onload_exl"
              @change="getfilepath"
            />
            <el-button
              @click="upload"
              :disabled="uploadBtn"
              style="cursor: pointer"
              >上传</el-button
            >
          </div>
        </el-dialog>
      </template>
      <!-- 导入周计划 -->
      <ImportExcel_plan ref="weekImportRef" />
      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column type="index" label="序号" width="55" align="center" />
        <el-table-column
          label="工厂编号"
          prop="plantCode"
          min-width="150"
          show-overflow-tooltip
          align="left"
        >
        </el-table-column>
        <el-table-column
          label="状态"
          prop="planState"
          min-width="100"
          show-overflow-tooltip
          align="center"
        >
          <template #default="scope">
            <el-tag v-show="scope.row.planState == 0" type="success">{{
              useDictionary("plannedBatchType", scope.row.planState ?? "")
            }}</el-tag>
            <el-tag v-show="scope.row.planState != 0">{{
              useDictionary("plannedBatchType", scope.row.planState ?? "")
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="计划年份"
          prop="planYear"
          min-width="100"
          show-overflow-tooltip
          align="center"
        >
          <template #default="scope"> {{ scope.row.planYear }}年 </template>
        </el-table-column>
        <el-table-column
          label="计划月份"
          prop="planMonth"
          min-width="100"
          show-overflow-tooltip
          align="center"
        >
          <template #default="scope"> {{ scope.row.planMonth }}月 </template>
        </el-table-column>
        <el-table-column
          label="存货编码"
          prop="materialCode"
          min-width="180"
          show-overflow-tooltip
          align="left"
        >
          <template #default="scope">
            {{ scope.row.materialCode }}-{{ scope.row.materialName }}
          </template>
        </el-table-column>
        <el-table-column
          label="图号"
          prop="figureNumber"
          min-width="180"
          show-overflow-tooltip
          align="left"
        >
        </el-table-column>
        <el-table-column
          label="计划批次"
          prop="planBatch"
          min-width="100"
          show-overflow-tooltip
          align="right"
        >
        </el-table-column>
        <el-table-column
          label="批次数量"
          prop="planBatchNum"
          min-width="100"
          show-overflow-tooltip
          align="right"
        >
        </el-table-column>
        <el-table-column
          label="完成报工数量"
          prop="planFinishQuantity"
          min-width="150"
          show-overflow-tooltip
          align="right"
        >
        </el-table-column>
        <el-table-column
          label="完成率"
          prop="plantCode"
          min-width="150"
          show-overflow-tooltip
          align="right"
        >
          <template #default="scope">
            {{
              getPercentage(
                scope.row.planFinishQuantity,
                scope.row.planBatchNum
              )
            }}%
          </template>
        </el-table-column>
        <el-table-column
          label="待判定数量"
          prop="invalidQuantity"
          min-width="150"
          show-overflow-tooltip
          align="right"
        >
        </el-table-column>
        <el-table-column
          label="计划剩余数量"
          prop="planFinishQuantity"
          min-width="150"
          show-overflow-tooltip
          align="right"
        >
          <template #default="scope">
            {{ scope.row.planBatchNum - scope.row.planFinishQuantity }}
          </template>
        </el-table-column>
        <el-table-column
          label="创建时间"
          prop="createTime"
          min-width="180"
          show-overflow-tooltip
          align="left"
        >
        </el-table-column>
        <!-- <el-table-column label="操作" align="center" width="100">
          <template #default="scope"> -->
        <!-- <el-button
              type="primary"
              size="small"
              link
              @click="openDialogdetail(scope.row)"
              ><i-ep-search />
              查看
            </el-button> -->
        <!-- <el-button
              type="primary"
              size="small"
              link
              @click="openDetails(scope.row)"
              ><i-ep-search />
              详情
            </el-button> -->
        <!-- <el-button
              type="primary"
              size="small"
              link
              @click="openDialog(scope.row)"
              ><i-ep-edit />编辑</el-button
            > -->
        <!-- <el-button
              type="primary"
              size="small"
              link
              @click="deleteItem(scope.row.id)"
              ><i-ep-delete />删除</el-button
            >
          </template>
        </el-table-column> -->
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <mesplannedbatch-edit
      :visible="addDialog.visible"
      :title="addDialog.title"
      :ceshi="addDialog.ceshi"
      :data="addDialog.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />
    <!-- <mesplannedbatch-select
      v-model:visible="addDialog123.visible"
      :title="addDialog123.title"
      :isMultiple="true"
      :data="addDialog123.data"
      :is-readonly="addDialog123.readvisible"
      @echo-info="getSelect"
      @change-visible="changeVisible1"
    /> -->
  </div>
</template>

<script setup lang="ts">
import { useTable, useDownload, useDictionary } from "@/utils/useTable";
import dayjs from "dayjs";
import request from "@/utils/request";
import {
  getFirstWorkShopList,
  getMesRouteGroupList,
  getWorkCenterDetail,
  getCurrentYield,
  getFreeDetails,
  getMonthList,
  getYearList,
  getMaterialList,
  getDateshiftCount,
  getOtherWorkShopList,
} from "@/utils/commonData";

import {
  getWeeksInYear,
  getWeekNumber,
  week_date,
  getDaysOfCurrentWeek,
} from "@/utils/dateUtils";

defineOptions({
  name: "MESMESPLANNEDBATCH",
  inheritAttrs: false,
});

// 请求参数
const requestApi = "/mes/mesplannedbatch/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = {};
const currentYear = new Date().getFullYear(); // 当前年份
const currentMonth = dayjs().month() + 1; // 当前年份
const currentWeek = getWeekNumber(new Date()); // 当前第几周
// 初始化搜索参数数据
const searchParamInit = {
  plantId: "",
  planState: "",
  plantCode: "",
  materialId: "",
  materialCode: "",
  planBatch: "",
  planWeek: currentWeek,
  planYear: currentYear,
  planMonth: currentMonth,
  figureNumber: "",
  materialIds: [],
};

const deleteParam = {
  api: "/mes/mesplannedbatch/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

// 获取年度列表
const yearOptions = ref();
// 获取周列表
// const monthOptions = ref<OptionType[]>();
const weekOptions = ref<OptionType[]>();

// 月份份
const monthOptions = [
  {
    id: 1,
    name: "1月",
  },
  {
    id: 2,
    name: "2月",
  },
  {
    id: 3,
    name: "3月",
  },
  {
    id: 4,
    name: "4月",
  },
  {
    id: 5,
    name: "5月",
  },
  {
    id: 6,
    name: "6月",
  },
  {
    id: 7,
    name: "7月",
  },
  {
    id: 8,
    name: "8月",
  },
  {
    id: 9,
    name: "9月",
  },
  {
    id: 10,
    name: "10月",
  },
  {
    id: 11,
    name: "11月",
  },
  {
    id: 12,
    name: "12月",
  },
];

const getPercentage = (finishQuantity: number, batchNum: number) => {
  return Number((finishQuantity / batchNum) * 100).toFixed(0);
};

const materialList = ref([]);
// 获取选中的数据进行回显并赋值
function getDevice(Ids: string[], Objects: any) {
  if (Ids.length > 0) {
    searchParam.value.materialIds = Ids;
  } else {
    searchParam.value.materialIds = [];
  }
  console.log(searchParam.value.materialIds);
}

const reset1 = () => {
  materialList.value = [];
  reset();
};

const reset2 = () => {
  searchParam.value.plantId = plantId.value;
  materialList.value = [];
};

onMounted(async () => {
  getTableList();
  getPlantList();
  // 获取年列表
  yearOptions.value = await getYearList();
  // 获取周搜索列表
  weekOptions.value = getMonthList(currentYear);
});

// 改变年份
const selectYear = (e) => {
  if (e) {
    searchParam.value = { ...searchParam.value, planWeek: "" };
    weekOptions.value = getMonthList(e);
  } else {
    weekOptions.value = [];
    searchParam.value = { ...searchParam.value, planWeek: "" };
  }
};
// 改变月份份
const selectMonth = (e) => {
  if (e) {
    searchParam.value.planMonth = e;
  } else {
    searchParam.value.planMonth = "";
  }
};
// 改变周
const selectWeek = (e) => {
  if (e) {
    searchParam.value.planWeek = e;
  } else {
    searchParam.value.planWeek = "";
  }
};

// 获取工厂列表
const plantId = ref("");
const plantList: any = ref([]);
const getPlantList = async () => {
  const res1 = await request({
    url: "system/sysOrganization/getList",
    method: "post",
    data: { organizationType: 3 },
  });
  plantList.value = res1.data;
  searchParam.value.plantId = plantList.value[0].id;
  plantId.value = plantList.value[0].id;
};
const companyId = ref("");
const searchedCompanyId = ref("");
const changePlant = () => {};
const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
  ceshi: [],
});

// 查询详情
async function getInfo(id: string) {
  request({
    url: `/mes/mesplannedbatch/get/${id}`,
    method: "get",
  })
    .then((data) => {
      addDialog.data = data.data;
      addDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}

/** 打开计划批次表单弹窗 */
const iiss = ref([]);
function openDialog(roleObj?: Object) {
  iiss.value = [];
  tableData.value.forEach((item: any) => {
    ids.value.forEach((i: any) => {
      if (i == item.id) {
        iiss.value.push(item);
      }
    });
  });
  addDialog.ceshi = iiss;
  console.log("22", addDialog.ceshi);
  if (roleObj) {
    addDialog.title = "修改计划批次";

    getInfo(roleObj.id);
  } else {
    addDialog.title = "新增计划批次";
    addDialog.visible = true;
  }
  addDialog.readvisible = false;
}

/** 打开计划批次表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "计划批次详情";
  getInfo(roleObj.id);
  addDialog.readvisible = true;
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}

function getcreateTime(data: any) {
  if (data) {
    searchParam.value.createTimeStart = data[0];
    searchParam.value.createTimeEnd = data[1];
  } else {
    searchParam.value.createTimeStart = "";
    searchParam.value.createTimeEnd = "";
  }
}
function getlastUpdateTime(data: any) {
  if (data) {
    searchParam.value.lastUpdateTimeStart = data[0];
    searchParam.value.lastUpdateTimeEnd = data[1];
  } else {
    searchParam.value.lastUpdateTimeStart = "";
    searchParam.value.lastUpdateTimeEnd = "";
  }
}

// 导入excel
const uploadApi = "/mes/mesplannedbatch/uploadClose";
const excelBox = ref(false);
const uploadBtn = ref(false);
const uploadFile = ref("");
const fileName = ref("");

function excelBoxOpen() {
  if (searchParam.value.planMonth == "") {
    ElMessage.warning({
      message: "请选择计划月份",
      type: "warning",
    });
    return;
  } else {
    excelBox.value = true;
  }
}

function getfilepath(e: any) {
  const file = e.target.files[0];
  fileName.value = file.name;
  uploadFile.value = file;
  uploadBtn.value = false;
}

function upload() {
  if (!uploadFile.value) {
    ElMessage({
      type: "warning",
      message: "请选择文件！",
    });
    return;
  }

  let formdata = new FormData();
  formdata.append("file", uploadFile.value);
  formdata.append("planMonth", searchParam.value.planMonth);
  let config = { headers: { "Content-Type": "multipart/form-data" } };
  request
    .post(uploadApi, formdata, config)
    .then((res) => {
      ElMessage({
        type: "success",
        message: "上传成功！",
      });

      excelBox.value = false;
      uploadBtn.value = true;
      search();
    })
    .catch((error) => {
      console.log(error);
    });
}

// 导入周数据
const weekImportRef = ref();
const uploadErrorRef = ref();
const errorDataList = ref([]);
async function weekImportApiFunc(formdata: FormData, config: any) {
  let data = await request
    .post("/mes/mesplannedbatch/uploadClose", formdata, config)
    .then((res: any) => {
      console.log(res);

      weekImportRef.value.resCode = res.code;
      console.log(res.code);
      weekImportRef.value.sucessTatol = res.data?.completeNo
        ? res.data.completeNo
        : "";
      if (res.data?.errorList?.length > 0) {
        errorDataList.value = res.data?.errorList;
        uploadErrorRef.value.errorBox = true;
      }
      console.log(res.code);

      if (res.code === 500) {
        weekImportRef.value.resCode = 500;
      }
    });
}
const weekBatchImport = () => {
  if (!searchParam.value.planMonth) {
    ElMessage.error("请选择计划月份，再操作");
  } else {
    let newSearchParam = { ...searchParam.value };
    let params = {
      title: "导入计划批次",
      tempApi: "/mes/mesplannedbatch/exportTemp", //模板下载
      importApi: weekImportApiFunc, // 导入
      getTableList: startSearch1, // 成功后回调
      isShowTemp: false,
      fileTypes: ".xls",
      searchParam: newSearchParam,
    };
    weekImportRef.value.acceptParams(params);
  }
};

const startSearch1 = () => {
  search();
};

async function deleteItem(id: any) {
  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    await request({
      url: `/mes/mesplannedbatch/delete`,
      method: "post",
      data: { ids: ids.value },
    }).then((res) => {
      ElMessage.success("删除成功！");
      search();
    });
  });
}

// 批量下达
const issueLoading = ref(false);
const issueOrders = () => {
  ElMessageBox.confirm("确认下达已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    issueLoading.value = true;
    await request({
      url: `/mes/mesplannedbatch/issue`,
      method: "post",
      data: { ids: ids.value },
    })
      .then((res) => {
        ElMessage.success("下达成功！");
        search();
      })
      .finally(() => {
        issueLoading.value = false;
      });
  });
};

// 批量关闭
const closeLoading = ref(false);
const closePlan = () => {
  ElMessageBox.confirm("确认关闭已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    closeLoading.value = true;
    await request({
      url: `/mes/mesplannedbatch/close`,
      method: "post",
      data: { ids: ids.value },
    })
      .then((res) => {
        ElMessage.success("关闭成功！");
        search();
      })
      .finally(() => {
        closeLoading.value = false;
      });
  });
};

// 批量删除
const deleteLoading = ref(false);
const deletePlan = () => {
  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    deleteLoading.value = false;
    await request({
      url: `/mes/mesplannedbatch/issueOrders`,
      method: "post",
      data: { ids: ids.value },
    })
      .then((res) => {
        ElMessage.success("删除成功！");
        search();
      })
      .finally(() => {
        deleteLoading.value = false;
      });
  });
};
// 批量变更提交
const changeSubLoading = ref(false);
const changeSubmission = () => {
  ElMessageBox.confirm("确认变更提交已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    changeSubLoading.value = false;
    await request({
      url: `/mes/mesplannedbatch/change`,
      method: "post",
      data: { ids: ids.value },
    })
      .then((res) => {
        ElMessage.success("变更提交成功！");
        search();
      })
      .finally(() => {
        changeSubLoading.value = false;
      });
  });
};

// const addDialog123 = reactive<DialogOption>({
//   visible: false,
//   title: "",
//   data: [],
// });
// function changeVisible1(value: boolean) {
//   addDialog123.visible = value;
//   if (!value) {
//     addDialog123.data = {};
//   }
// }

// const materialIdsList = ref([]);

// // 接收 人员选择器回调参数
// function getSelect(options: any) {
//   console.log(options);
//   // for (const value of options) {
//   //   console.log(value); // 输出: 1, 2, 3
//   //   formData.mesProduceTransferFormDTOS.push(value);
//   // }
//   // formData.mesProduceTransferFormDTOS = uniqueByProperty(
//   //   formData.mesProduceTransferFormDTOS,
//   //   "id"
//   // );
//   // console.log(formData.mesProduceTransferFormDTOS);
// }

// /** 打开外协发货单表单弹窗 */
// function openDialogAdd() {
//   addDialog123.title = "存货编码选择";
//   addDialog123.visible = true;
// }
</script>
